package com.cn.kabalifeuser.ui.my.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.BasePresenter;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.base.MyApplication;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.ui.login.AgreementActivity;
import com.cn.kabalifeuser.ui.login.LoginActivity;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.my.bean.AppVersionBean;
import com.cn.kabalifeuser.ui.my.bean.MyUserInfoBean;
import com.cn.kabalifeuser.ui.my.bean.NumBean;
import com.cn.kabalifeuser.ui.my.bean.UpImgBean;
import com.cn.kabalifeuser.ui.my.bean.UpPhoneActivity;
import com.cn.kabalifeuser.utils.GlideEngine;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.SPUtil;
import com.cn.kabalifeuser.utils.TimeUtils;
import com.flyco.roundview.RoundTextView;
import com.kongzue.dialog.listener.OnMenuItemClickListener;
import com.kongzue.dialog.v2.BottomMenu;
import com.kongzue.dialog.v2.SelectDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.db.CacheManager;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 晓林 on 2020/9/3.
 * function:
 */
public class UserInfoActivity extends IBaseActivity<UserInfoView, UserInfoPresenter> implements UserInfoView {
    @BindView(R.id.img_user_head)
    CircleImageView imgUserHead;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_sex)
    TextView tvUserSex;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_user_address)
    TextView tvUserAddress;
    @BindView(R.id.tv_edition)
    TextView tvEdition;

    @BindView(R.id.tv_msg)
    RoundTextView tv_msg;


    public final static int CHOOSE_PHOTO_1 = 1001;
    private List<LocalMedia> selectHead = new ArrayList<>();
    String pathHead = "";//头像地址
    private int themeId;//
    private String[] choosePhotos;


    OptionsPickerView optionsPickerViewSex;
    private ArrayList<NumBean> itemOptionsSex = new ArrayList<>();
    AppVersionBean appVersionBean;

    @Override
    protected UserInfoPresenter createPresenter() {
        return new UserInfoPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_userinfo;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setTitleBar("个人资料");
        choosePhotos = new String[]{getResources().getString(R.string.main_img_photograph), getResources().getString(R.string.main_img_album)};
        ///样式
        themeId = R.style.picture_default_style;
        tvEdition.setText("v " + MyApplication.getVersionName());

        mPresenter.onAppVersionData(LoginHelper.getLonginData().getResult());

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onUserInfoData(LoginHelper.getLonginData().getResult());
    }

    @OnClick({R.id.ll_btn_about_us, R.id.ll_btn_privacy, R.id.ll_btn_version, R.id.ll_btn_head, R.id.ll_btn_name, R.id.ll_btn_sex, R.id.ll_btn_phone, R.id.ll_btn_address, R.id.tv_btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_btn_head:
                showBottomMenu(choosePhotos);
                break;
            case R.id.ll_btn_name:
                Bundle bundle = new Bundle();
                bundle.putString("name", tvUserName.getText().toString().trim());
                $startActivity(UserInfoNameActivity.class, bundle);
                break;
            case R.id.ll_btn_sex:
                if (optionsPickerViewSex != null && itemOptionsSex.size() > 0) {
                    optionsPickerViewSex.show();
                } else {
                    setSexData();
                    setStoreSexData();
                    optionsPickerViewSex.show();
                }
                break;
            case R.id.ll_btn_phone:

                $startActivity(UpPhoneActivity.class);

                break;
            case R.id.ll_btn_about_us:
                $startActivity(AboutUsActivity.class);
                break;
            case R.id.ll_btn_address:
                bundle = new Bundle();
                bundle.putInt("sign", 1);
                $startActivity(IAddressListActivity.class, bundle);
                break;
            case R.id.tv_btn_next:
                SelectDialog.show(getMe(), "提示", "确定要退出吗？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.onUserOutData(LoginHelper.getLonginData().getResult());
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
            case R.id.ll_btn_version:
                if (appVersionBean != null) {
                    if (MyApplication.getVersionName().equals(appVersionBean.getResult().getVersion())) {
                        RxToast.success("当前已是最新版本");
                    } else {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(appVersionBean.getResult().getUrl());
                        intent.setData(content_url);
                        startActivity(intent);
                    }
                }
                break;
            case R.id.ll_btn_privacy:
                bundle = new Bundle();
                bundle.putInt("sign", 2);
                $startActivity(AgreementActivity.class, bundle);
                break;
        }
    }

    /**
     * 展示底部菜单选择
     *
     * @param strings 数组
     */
    private void showBottomMenu(String[] strings) {
        BottomMenu.show(this, strings, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                switch (index) {
                    case 1://TODO 相册
                        PictureSelector.create(UserInfoActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(themeId)
                                .selectionMode(PictureConfig.SINGLE)
                                .imageSpanCount(4)
                                .previewImage(true)
                                .isCamera(true)
                                .enableCrop(true)// 是否裁剪
                                .compress(true)// 是否压缩
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                .scaleEnabled(true)
                                .withAspectRatio(18, 18)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .forResult(CHOOSE_PHOTO_1);


                        break;
                    case 0://TODO 相机
                        // 单独拍照
                        PictureSelector.create(UserInfoActivity.this)
                                .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(themeId)
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .enableCrop(true)// 是否裁剪
                                .compress(true)// 是否压缩
                                .scaleEnabled(true)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                .withAspectRatio(18, 18)
                                .openClickSound(true)// 是否开启点击声音
                                .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .forResult(CHOOSE_PHOTO_1);//结果回调onActivityResult code
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
//            case onActivityResult_To_ComName:
//                if (data != null) {
//                    String name = data.getStringExtra("name");
//                    tvName.setText(name);
////                    String time = TimeUtils.getTime10();
////                    mPresenter.onUpUserInfoData(time, 1, name, LoginHelper.getLonginData().getInfo().getUuid());
//                }
//                break;
            case RESULT_OK:
                switch (requestCode) {
                    case CHOOSE_PHOTO_1:
                        // 图片选择结果回调
                        selectHead = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                        for (LocalMedia media : selectHead) {
                            Log.i("图片-----》", media.getPath());

                            if (media.isCut() && !media.isCompressed()) {
                                // 裁剪过
                                pathHead = media.getCutPath();
                            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                                pathHead = media.getCompressPath();
                            } else {
                                // 原图
                                pathHead = media.getPath();
                            }
                            LoggerUtils.d("图片的地址=" + pathHead);
                            Glide.with(this).load(pathHead).into(imgUserHead);
                            //todo 上传头像
                            mPresenter.onUpImgData("head", pathHead);
                        }
                        break;
                }
            default:
                break;

        }
    }

    /**
     * 性别
     */
    private void setSexData() {
        itemOptionsSex.add(new NumBean(1, "男"));
        itemOptionsSex.add(new NumBean(2, "女"));
    }

    /**
     * 性别
     */
    private void setStoreSexData() {
        optionsPickerViewSex = new OptionsPickerBuilder(getMe(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx1 = itemOptionsSex.get(options1).getPickerViewText();
                tvUserSex.setText(tx1);
                mPresenter.onUpUserInfoSexData(LoginHelper.getLonginData().getResult(), tx1.equals("男") ? "1" : "2");
            }
        }).setLayoutRes(R.layout.pw_store, new CustomListener() {
            @Override
            public void customLayout(View v) {
                TextView iv_cancel = v.findViewById(R.id.tv_cancel);
                TextView tvSubmit = v.findViewById(R.id.tv_next);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        optionsPickerViewSex.returnData();
                        optionsPickerViewSex.dismiss();
                    }
                });

                iv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        optionsPickerViewSex.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        optionsPickerViewSex.setPicker(itemOptionsSex);//添加数据
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onUpImgSuccess(UpImgBean bean) {
        mPresenter.onUpUserInfoData(LoginHelper.getLonginData().getResult(), bean.getResult().get(0));
    }

    @Override
    public void onUpUserInfoSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());

    }

    @Override
    public void onUserInfoSuccess(MyUserInfoBean bean) {
        GlideUtil.ImageLoad(getMe(), bean.getResult().getHead(), imgUserHead);
        tvUserName.setText(bean.getResult().getNickname());
        tvUserSex.setText(bean.getResult().getSex() == 1 ? "男" : "女");
        tvUserPhone.setText(bean.getResult().getPhone());


    }

    @Override
    public void onUserOutSuccess(MsgBean bean) {
        SPUtil.clear();    //清除 保存本地的数据
        boolean isClear = CacheManager.getInstance().clear();
        Logger.e("清除OKgo缓存~" + isClear);
        LoginHelper.getLocationInfo().clearSPlocationData();
        RxToast.success(bean.getMsg());
        $startActivityFinish(LoginActivity.class);
        //除了登录activity不关闭。其余的都关闭。
        MyApplication.getInstance().getActivityManager().popAllActivityExceptOne(LoginActivity.class);
    }

    @Override
    public void onAppVersionSuccess(AppVersionBean bean) {
        appVersionBean = bean;
        if (MyApplication.getVersionName().equals(bean.getResult().getVersion())) {
            tv_msg.setVisibility(View.GONE);
        } else tv_msg.setVisibility(View.VISIBLE);
    }
}
